import { Body, Controller, Get, Head, Post, Query, ValidationPipe } from '@nestjs/common'
import { UserService } from './user.service'
import { suc, fail } from '../utils/response'
import { User } from 'src/entities/user.entity'

@Controller('user')
export class UserController {
  constructor(private readonly userSrvice: UserService) {}

  @Post('register')
  async register(@Body(ValidationPipe) body): Promise<any> {
    const { username, password } = body

    const userInfo: User = await this.userSrvice.findOne({ username })
    if (userInfo) return fail('该用户名已被注册')

    await this.userSrvice.save({
      username,
      password
    })
    return suc({}, '注册成功')
  }

  @Post('login')
  async login(@Body(ValidationPipe) body): Promise<any> {
    const { username, password } = body

    const userInfo: User = await this.userSrvice.findOne({ username })
    if (!userInfo) return fail('用户名不存在')

    await this.userSrvice.updateToken({ id: userInfo.id })

    const data: User = await this.userSrvice.findOne({
      username,
      password
    })
    return data ? suc(data, '登录成功') : fail('密码错误')
  }
}
